package com.dingdang.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.dingdang.entity.TbCarGoods;
import com.dingdang.service.EsSearchService;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MatchPhraseQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class EsSearchServiceImpl implements EsSearchService {

    @Resource
    private RestHighLevelClient client;

    @Override
    public Map<String,Object> selectInfo(String title, Integer pageNum, Integer pageSize) {
        //这里写从es中查询的条件
        //设置请求的对象,设置查询的索引库
        SearchRequest request = new SearchRequest("dingdangcar");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //搜索title
        //MatchQueryBuilder queryBuilder = QueryBuilders.matchQuery("title", title);
        //这个是精确模糊搜索
        MatchPhraseQueryBuilder queryBuilder = QueryBuilders.matchPhraseQuery("title", title);
        searchSourceBuilder.query(queryBuilder);

        //设置一下排序,默认是升序
        searchSourceBuilder.sort("sort");

        //设置高亮的字段
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title");
        //设置高亮的样式
        highlightBuilder.preTags("<font color='red'>");
        highlightBuilder.postTags("</font>");
        //将高亮放入请求中
        searchSourceBuilder.highlighter(highlightBuilder);

        //设置分页
        searchSourceBuilder.from((pageNum-1) * pageSize);
        searchSourceBuilder.size(pageSize);

        //将所有的请求放入request中
        request.source(searchSourceBuilder);

        //准备数据
        List<TbCarGoods> list = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        long totalHits = 0;
        try {
            //调用方法进行通讯
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            //获取结果
            SearchHit[] hits = response.getHits().getHits();
            //获取总条数
            totalHits = response.getHits().getTotalHits();
            //循环遍历
            for (SearchHit hit : hits) {
                //获取普通内容
                String sourceAsString = hit.getSourceAsString();
                //将普通内容转换成实体类类型
                TbCarGoods tbCarGoods = JSONObject.parseObject(sourceAsString, TbCarGoods.class);
                //获取高亮的字段
                Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                //解析高亮的结果
                HighlightField highlightField = highlightFields.get("title");
                Text[] fragments = highlightField.getFragments();
                for (Text fragment : fragments) {
                    //获取高亮的字段并且set给实体类
                    tbCarGoods.setTitle(fragment.toString());
                }
                list.add(tbCarGoods);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        map.put("list",list);
        map.put("total",totalHits);
        //返回结果
        return map;
    }

    @Override
    public Map<String, Object> selectCondition(Long carInformationId, Long carTypeId, Long kilometersTraveled,
                                               String assessmentId, String transferNum, String carDisplacement) {
        SearchRequest request = new SearchRequest("dingdangcar");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        if (carInformationId != null){
            boolQueryBuilder.must(QueryBuilders.matchQuery("car_information_id",carInformationId));
        }else if (carTypeId != null){
            boolQueryBuilder.must(QueryBuilders.matchQuery("car_type_id",carTypeId));
        }else if (kilometersTraveled != null){
            boolQueryBuilder.must(QueryBuilders.matchQuery("kilometers_traveled",kilometersTraveled));
        }else if (StringUtils.isNoneBlank(assessmentId)){
            boolQueryBuilder.must(QueryBuilders.matchQuery("assessment_id",assessmentId));
        }else if (StringUtils.isNoneBlank(transferNum)){
            boolQueryBuilder.must(QueryBuilders.matchQuery("transfer_num",transferNum));
        }else {
            boolQueryBuilder.must(QueryBuilders.matchQuery("car_displacement",carDisplacement));
        }

        searchSourceBuilder.query(boolQueryBuilder);

        //设置一下排序,默认是升序
        searchSourceBuilder.sort("sort");

        //将所有的请求放入request中
        request.source(searchSourceBuilder);

        //准备数据
        List<TbCarGoods> list = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        long totalHits = 0;
        try {

            //调用方法进行通讯
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            //获取结果
            SearchHit[] hits = response.getHits().getHits();
            //获取总条数
            totalHits = response.getHits().getTotalHits();
            //循环遍历
            for (SearchHit hit : hits) {
                //获取普通内容
                String sourceAsString = hit.getSourceAsString();
                //将普通内容转换成实体类类型
                TbCarGoods tbCarGoods = JSONObject.parseObject(sourceAsString, TbCarGoods.class);
                list.add(tbCarGoods);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        map.put("list",list);
        map.put("total",totalHits);
        //返回结果
        return map;

    }
}
